package com.typing.battle.activity;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import com.typing.battle.R;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.util.C2dmUtil;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class TypingBattleIndexActivity extends TypingBattleRootActivity {
	/** Called when the activity is first created. */
	private PreferenceMgr mgr;
	private String phoneNum;
	private Button btnJoin;
	private EditText email,password,passwordRepeat,name,descript;
	private RadioButton sex_m;
	private RadioButton sex_f;
	private EditText age;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.battle_index);
		
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		phoneNum = tm.getLine1Number();		
		
		mgr = PreferenceMgr.getInstance(this);
		if ("".equals(mgr.getData(PreferenceMgr.REGISTRATION_KEY, ""))) {
			C2dmUtil.getRegistrationId(this);
		}
		btnJoin = (Button)findViewById(R.id.btn_join);
		btnJoin.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				checkAndRequest();
				
			}
		});		
	}	
	public void checkAndRequest(){
		email = (EditText)findViewById(R.id.input_email);
		password = (EditText)findViewById(R.id.input_password);
		passwordRepeat = (EditText)findViewById(R.id.input_password_repeat);
		name = (EditText)findViewById(R.id.input_name);
		descript = (EditText)findViewById(R.id.input_descript);
		sex_m = (RadioButton)findViewById(R.id.input_sex_m);
		sex_f = (RadioButton)findViewById(R.id.input_sex_f);
		age = (EditText)findViewById(R.id.input_age);
		
		String str = "^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$";
		Pattern p = Pattern.compile(str);
		
		Matcher m = p.matcher(email.getText().toString()); 

        System.out.println("source:"+email.getText().toString()); 
        
		
        String msg = null;
        if(!m.find()){
        	msg = "이메일형식이 맞지 않습니다.";
        	Log.d("email TEST", "not match");
        }else if(!password.getText().toString().equals(passwordRepeat.getText().toString())){
        	msg = "패스워드가 정확하지 않습니다.";
        	Log.d("password TEST", "not match");
        }else if("".equals(age.getText().toString())){
        	msg = "나이를 입력해주세요.";
        	Log.d("age TEST", "not input");
		}else if(!sex_m.isChecked() && !sex_f.isChecked()){
			msg = "성별을 선택해주세요.";
			Log.d("sex TEST", "not choice");
		}
        
        if(msg != null){
        	Toast toast = Toast.makeText(this, msg,
    				Toast.LENGTH_SHORT);
//    		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
    		toast.show();
    		return;
        }else{
        	ServerComunicationDTO dto = new ServerComunicationDTO();
        	dto.setUserEmail(email.getText().toString());
        	dto.setUserPassword(password.getText().toString());
        	dto.setUserRegKey(mgr.getData(PreferenceMgr.REGISTRATION_KEY, ""));
        	dto.setUserPhoneNo(phoneNum);
        	dto.setUserName(name.getText().toString());
        	dto.setUserDescription(descript.getText().toString());
        	dto.setUserAge(age.getText().toString());
        	dto.setUserSex(sex_m.isChecked()?"M":"F");
        	dto.setActionType(ServerComunicationUtil.TYPE_MEMBER_JOIN);
        	dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
        	try{
        		ServerComunicationUtil.serverAction(dto,this,this);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	
//        	setResult(TypingBattleLoginActivity.LOGIN_RESULT_REGISTER);
//        	finish();
//        	login();
//        	Intent intent = new Intent(TypingBattleIndexActivity.this,TypingBattleMainActivity.class);			
//			startActivity(intent);
//			finish();
        }
	}
//	public void login(){
//		ServerComunicationDTO dto = new ServerComunicationDTO();
//		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY,""));
//		dto.setUserPassword(mgr.getData(PreferenceMgr.USER_PASSWORD_KEY,""));
//		//dto.setUserPassword("asdf1234");
//		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
//		try{
//			Log.d("로그인시작","시작");
//			ServerComunicationUtil.SESSION_KEY = (String)ServerComunicationUtil.login(dto,this);
//			finish();
//		}catch(Exception e){
//			e.printStackTrace();
//			//Log.d("에러에러",e);
//		}
//	}
	
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_MEMBER_JOIN){
				try{
		        	mgr.setData(PreferenceMgr.USER_EMAIL_KEY, dto.getUserEmail());
		        	mgr.setData(PreferenceMgr.USER_PASSWORD_KEY, dto.getUserPassword());
		        	mgr.setData(PreferenceMgr.USER_NAME_KEY, dto.getUserName());
		        	mgr.setData(PreferenceMgr.USER_DESCRIPT_KEY, dto.getUserDescription());
		        	mgr.setData(PreferenceMgr.USER_AGE_KEY, dto.getUserAge());
		        	mgr.setData(PreferenceMgr.USER_SEX_KEY, dto.getUserSex());
		        	mgr.setData(PreferenceMgr.PHONE_NUMBER_KEY,phoneNum);
		        	setResult(TypingBattleLoginActivity.LOGIN_RESULT_REGISTER);
		        	finish();
				}catch(Exception e){
					e.printStackTrace();
				}
			}		
		}
		super.onSyncComplete(resultCode, dto, resultObj);
	}
}